package com.xm.swagger.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.xm.common.entity.ResConst;
import io.swagger.annotations.Api;
import org.springframework.context.annotation.*;
import org.springframework.http.HttpMethod;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Response;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.*;
import java.util.stream.Collectors;

@EnableKnife4j
@EnableSwagger2
@Configuration
@Import(BeanValidatorPluginsConfiguration.class)
@Profile({"dev", "test"})
public class Swagger {

    /**
     * 通过构造注入所有Docket的方式
     * 触发FactoryBean的getObject方法
     *
     * @param dockets 所有Docket
     */
    public Swagger(List<Docket> dockets) {

    }

    /**
     * 默认的Docket
     *
     * @return Docket
     */
    @Bean
    public Docket docket() {
        SwaggerGroups.SwaggerGroup swaggerGroup = new SwaggerGroups.SwaggerGroup();
        swaggerGroup.setGroupName("a.全部");
        return Swagger.build(swaggerGroup);
    }

    public static Docket build(SwaggerGroups.SwaggerGroup swaggerGroup) {
        // 添加全局响应码
        List<Response> responses = Arrays.stream(ResConst.values())
                .map(e -> new Response(String.valueOf(e.getCode()), e.getMessage(),
                        false, Collections.emptyList(), Collections.emptyList(),
                        Collections.emptyList(), Collections.emptyList()))
                .collect(Collectors.toList());
        HttpMethod[] httpMethods = HttpMethod.values();
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        for (HttpMethod httpMethod : httpMethods) {
            docket.globalResponses(httpMethod, responses);
        }
        return docket
                .apiInfo(new ApiInfoBuilder()
                        .title(swaggerGroup.getTitle())
                        .description(swaggerGroup.getDescription())
                        .termsOfServiceUrl(swaggerGroup.getUrl())
                        .version(swaggerGroup.getVersion())
                        .build())
                .select()
                .apis(Objects.isNull(swaggerGroup.getBasePackage()) ?
                        RequestHandlerSelectors.withClassAnnotation(Api.class) :
                        RequestHandlerSelectors.basePackage(swaggerGroup.getBasePackage()))
                .paths(PathSelectors.any()).build()
                .forCodeGeneration(true)
                .groupName(swaggerGroup.getGroupName());
    }

}
